package com.king.wxpay.util;

import javax.net.ssl.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * HTTP工具类
 * @author taomk
 * @version 1.0
 * @since 15-7-10 下午4:08
 */
public class SimpleHttp {
	private static final Log log = LogFactory.getLog(SimpleHttp.class);
	private HttpURLConnection con;
	private URL url;

	public SimpleHttp(String urlstr) {
		try {
			url = new URL(urlstr);
			con = (HttpURLConnection) url.openConnection();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void connect() {
		try {
			this.con.connect();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void commonConfig(String method, boolean doInput, boolean doOutput) {
		try {
			con.setRequestMethod(method);
			con.setDoInput(doInput);
			con.setDoOutput(doOutput);
		} catch (Exception e) {
			log.info(e.toString());
		}
	}

	public HttpURLConnection getConnection() {
		return this.con;
	}

	public void writeBytes(byte[] bytes) {
		try {
			OutputStream os = con.getOutputStream();
			os.write(bytes);
			os.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public byte[] readBytes() {
		try {
			InputStream in = con.getInputStream();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			int c = 0;
			byte[] buf = new byte[512];
			while ((c = in.read(buf)) > 0)
				os.write(buf, 0, c);
			return os.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String readString(String charset) {
		try {
			byte[] bytes = this.readBytes();
			return new String(bytes, charset);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void setSSLContext(KeyManager[] keyManagers, TrustManager[] trustManagers) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(keyManagers, trustManagers, null);
			HttpsURLConnection httpsCon = (HttpsURLConnection) con;
			httpsCon.setSSLSocketFactory(ctx.getSocketFactory());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void setHostnameVerifier(HostnameVerifier verifier) throws Exception {
		HttpsURLConnection httpsCon = (HttpsURLConnection) con;
		httpsCon.setHostnameVerifier(verifier);
		HttpsURLConnection.setDefaultHostnameVerifier(verifier);
	}

	public static class DefaultHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			log.info("target host:" + hostname);
			return true;
		}
	}

	public URL getURL() {
		return this.url;
	}
}
